<?php
/**
 * Created by PhpStorm.
 * User: Auser
 * Date: 2017/5/23
 * Time: 9:19
 */

namespace App\Admin\Controllers;

use App;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;

use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Table;
use Encore\Admin\Widgets\Carousel;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Chart\Bar;
use Encore\Admin\Widgets\Chart\Doughnut;
use Encore\Admin\Widgets\Chart\Pie;
use Encore\Admin\Widgets\Chart\PolarArea;
use Encore\Admin\Widgets\Collapse;
use Encore\Admin\Widgets\InfoBox;
use Encore\Admin\Widgets\Form;
use DecreaseUserInfoHelper;
use App\Admin\Extensions\timeLine;
use App\Admin\Extensions\tileimg;
use App\Services\MyPermission;

use Illuminate\Support\Facades\DB;
use App\Models\JzOrderDetail;
use App\Models\JzMatchRelation;
use JzOrderDetailService;
use UserRecordService;
use JzMatchRelationService;
use WechatUserService;
use TestingDetailService;
use DecreaseSelectHelper;
use ParamConfig;
use TestingConfig;
use App\Models\ChinaArea;
use App\Models\WechatUser;
use Illuminate\Support\Facades\Input;
class DecreaseSelectController
{

    use ModelForm;

    public function index(Request $request){
        return Admin::content(function (Content $content)use($request) {
            $content->header(trans('backend.decrease_user.header.title'));
            $content->row(function (Row $row) use ($request) {
                $row->column(12, function (Column $column) use ($request) {
                    $str= "";
                    $appid = $request->input('appid');
                    $form = new Form($request->input());
                    $form->action('/admin/testing/decrease/select/index'."?appid=".$appid);
                    $form->method('POST');
                    $form->date('order_time',trans('backend.decrease_user.select.order_time'));
                    $form->date('start_time',trans('backend.decrease_user.select.start_time'));
                    $form->select('principal',trans('backend.decrease_user.select.principal'))->options(DecreaseSelectHelper::getNutritionist());
                    $form->select('from',trans('backend.decrease_user.select.from'))->options(json_decode(ParamConfig::getValue('JZ.admin.oder.user.from'),true));
                    $form->select('tid',trans('backend.decrease_user.select.testing'))->options(json_decode(ParamConfig::getValue('JZ.admin.oder.user.good_title'),true));
                    $form->text('phone',trans('backend.decrease_user.select.phone'));
                    $form->text('number',trans('backend.decrease_user.select.number'));
                    $form = $form.'<a href="/admin/testing/decrease/add/index?appid='.$appid.'" style="width: 88px;height: 72px;border-radius: 0 0 0 89px;background-color: #3c8dbc;color: #fff;position: absolute;right: -14px;top: -14px;line-height: 70px;text-indent: 18px;text-decoration: none;">+添加用户</a>';
                    $column->append((new Box(trans('backend.decrease_user.select.title'), $form))->style('info'));
                });

            });

            $content->row(function (Row $row) use($request){
                $row->column(12, function (Column $column)use($request) {
                    $column->append((new Box('用户列表',$this->grid($request)))->style('info'));
                });
            });
        });

    }

    protected function grid($request)
    {
        return Admin::grid(JzOrderDetail::class, function (Grid $grid)use($request){
            $where = array();
            $oid = array();
            $data = $request->input();
            foreach($data as $k => $v){
                if(empty($v) || $v == "0"){
                    unset($data[$k]);
                }
            }
            $appidDecode = base64_decode($request->input('appid'));
            $appid =  ['appid', '=',$appidDecode];
            array_push($where,$appid);
            if(isset($data['principal'])){
                $principal = ['principal', '=',$data['principal']];
                array_push($where,$principal);
            }
            if(isset($data['from'])){
                $from = ['from', '=', $data['from']];
                array_push($where,$from);
            }
            if(isset($data['tid'])){
                $tid = ['tid', '=', $data['tid']];
                $oid = DecreaseSelectHelper::filterUser($appidDecode,$data['tid']);
                array_push($where,$tid);
            }else{
                $oid = DecreaseSelectHelper::filterUser($appidDecode);
            }
            if(isset($data['order_time'])){
                $order_time = ['order_time', 'like', "%".$data['order_time']."%"];
                array_push($where,$order_time);
            }
            if(isset($data['start_time'])){
                $start_time = ['start_time', 'like', "%".$data['start_time']."%"];
                array_push($where,$start_time);
            }
            if(isset($data['phone'])){
                $phone = ['phone', 'like', "%".$data['phone']."%"];
                array_push($where,$phone);
            }
            if(isset($data['number'])){
                $number = ['number', 'like', "%".$data['number']."%"];
                array_push($where,$number);
            }
            $grid->model()->where($where)->whereIn('id', $oid)->orderBy('id', 'desc');
            $grid->id('ID')->sortable();
            $grid->nick_name(trans('backend.decrease_user.form.name'));
            $grid->testing(trans('backend.decrease_user.form.testing'));
            $grid->phone(trans('backend.decrease_user.form.phone'));
            $grid->order_time(trans('backend.decrease_user.form.order_time'))->display(function($order_time){
                return date('Y-m-d', strtotime($order_time));
            });
            $grid->testing_time(trans('backend.decrease_user.form.testing_time'));
            $grid->number(trans('backend.decrease_user.form.number'));
            $grid->principal(trans('backend.decrease_user.add.principal'));
            $grid->rows(function($row)use($request,$appidDecode){
                $relation = JzMatchRelationService::getByOid($row->id);
                if($relation){
                    $nic_name = WechatUserService::getNickNameByUid($relation->uid);
                    $row->column('nick_name',$nic_name);
                    $testing = TestingDetailService::getNameByTid($relation->tid);
                    $row->column('testing',$testing);
                    $recode = UserRecordService::getByUid($relation->uid,$relation->tid);
                    if($recode){
                        $arr = json_decode( json_encode($recode),true);
                        $html = "<a href='/admin/testing/decrease/user/info/".$arr['id']."/".$arr['uid']."/".$arr['tid']."/".$request->input('appid')."'><i class='fa fa-eye'></i></a>";
                        $row->column('testing_time',$arr['created_at']);
                    }else{
                        $row->column('testing_time','-- -- -- --');
                        $html = "<a href='/admin/testing/decrease/user/info/0/".$relation->uid."/".$relation->tid."/".$request->input('appid')."'><i class='fa fa-eye'></i></a>";
                    }
                }
                $row->actions('');
                $row->actions()->add(function($row)use($request,$html) {
                  return $html;
                });
                if(MyPermission::check('delete')) {
                    $row->actions()->add(function ($row)use($request) {
                        return "<a href='/admin/testing/decrease/delete/order/".$request->input('appid')."/{$row->id}'><i class='fa fa-trash'></i></a>";
                    });
                }
            });
            $grid->disableFilter();
            $grid->disableBatchDeletion();
            $grid->disableCreation();
            $grid->disableExport();

        });

    }



    /**添加订单首页
     * @param Request $request
     * @return mixed
     */
    public function addIndex(Request $request){
        return Admin::content(function (Content $content)use($request) {
            $content->header(trans('backend.decrease_user.header.title'));
            $content->row(function (Row $row) use ($request) {
                $row->column(12, function (Column $column) use ($request) {
                    $oid = empty($request->input('id')) ? "" : $request->input('id');
                    $appid = $request->input('appid');
                    $data = DecreaseSelectHelper::orderEditInfo($oid,base64_decode($appid));
                    $str= "";
                    if($request->input('uid') && $request->input('rid')){
                        $data['rid']=$request->input('rid');
                        $data['uid']=$request->input('uid');
                    }
                    $form = new Form($data);

                     $form->action('/admin/testing/decrease/add/order'."?appid=".$request->input('appid'));
                    $form->method('POST');
                    $form->text('shouhuo_name', trans('backend.decrease_user.add.name'));
                    $form->text('buyer_name', trans('backend.decrease_user.add.member'));
                    $form->select('buyer_sex',trans('backend.decrease_user.add.sex'))->options(['男'=>'男','女'=>'女']);

                    $form->select('province',trans('backend.decrease_user.add.province').'-(必选)')->options(function(){
                       $province =  ChinaArea::province()->pluck('name', 'id')->toArray();
                        return $province;
                    })->load('city', '/admin/api/china-area/city');

                    $form->select('city',trans('backend.decrease_user.add.city').'-(必选)')->options(function ($id=52) {
                        return ChinaArea::options($id);
                    })->load('district', '/admin/api/china-area/district');

                    $form->select('district',trans('backend.decrease_user.add.area').'-(必选)')->options(function ($id=500) {
                        return ChinaArea::options($id);
                    });
                    $form->text('shouhuo_address', trans('backend.decrease_user.add.addresss'));
                    $form->text('phone', trans('backend.decrease_user.add.phone'));
                    $form->text('wuliu', trans('backend.decrease_user.add.wuliu'));
                    $form->text('wuliu_id', trans('backend.decrease_user.add.wuliuid'));
                    $form->text('order_id', trans('backend.decrease_user.add.orderid'));
                    $form->text('order_status', trans('backend.decrease_user.add.status'));
                    $form->select('from',trans('backend.decrease_user.select.from'))->options(json_decode(ParamConfig::getValue('JZ.admin.oder.user.from'),true));
                    $form->text('good_title',trans('backend.decrease_user.select.good_title'));
                    if(!$oid){
                        $form->select('tid',trans('backend.decrease_user.select.testing').'-(必填)')->options(json_decode(ParamConfig::getValue('JZ.admin.oder.user.good_title'),true));
                    }else{
                        $form->hidden('tid');
                        //编辑,增加跳转不同地址的判断
                        $form->hidden('rid');
                        $form->hidden('uid');
                    }
                    $form->hidden('appid');
                    $form->hidden('id');
                    $form->text('nick_name', trans('backend.decrease_user.add.nickname'));
                    $form->text('good_message', trans('backend.decrease_user.add.good'));
                    $form->text('order_message', trans('backend.decrease_user.add.order'));
                    $form->select('principal',trans('backend.decrease_user.add.principal'))->options(DecreaseSelectHelper::getNutritionist());
                    $form->text('number', trans('backend.decrease_user.add.number'));
                    $form->date('order_time',trans('backend.decrease_user.select.order_time'));
                    $form->date('start_time',trans('backend.decrease_user.select.start_time'));
                    $form = $form.'<a href="/admin/testing/decrease/upload/index?appid='.$request->input('appid').'" style="width: 88px;height: 72px;border-radius: 0 0 0 89px;background-color: #3c8dbc;color: #fff;position: absolute;right: -14px;top: -14px;line-height: 70px;text-indent: 18px;text-decoration: none;">上传文档</a>';
                    $column->append((new Box(trans('backend.decrease_user.add.header'), $form))->style('info'));
                });
            });
        });
    }


    /**手动添加单个用户
     * @param Request $request
     */
    public function addOrder(Request $request){
        $data = $request->input();
        if(!isset($data['city'])){
            die('请选择城市');
        }
        if(empty($data['district'])){
            die('请选择区县');
        }
        if($data['tid'] == "0"){
            die('请选择所属测评');
        }
        $uid = "";
        if(isset($data['uid'])){
            $uid = $data['uid'];
            unset($data['uid']);
        }
        $rid = "";
        if(isset($data['rid'])){
            $rid = $data['rid'];
            unset($data['rid']);
        }
        $id =   DecreaseSelectHelper::storeOrder($data);
        $base_url = TestingConfig::getValue('website_url');
        if($uid && $rid){
            $redirect = $base_url.'/admin/testing/decrease/user/info/'.$rid.'/'.$uid.'/'.$data['tid'].'/'.base64_encode($request->input('appid'));
        }else{
            $redirect = $base_url.'/admin/testing/decrease/order/info?appid='.base64_encode($request->input('appid')).'&id='.$id;
        }
        redirectToUrl($redirect);
    }



    /**个人订单详情
     * @param Request $request
     * @return mixed
     */
    public function orderInfo(Request $request){
        return Admin::content(function (Content $content)use($request) {
            $content->header(trans('backend.decrease_user.header.title'));
            $content->row(function (Row $row) use ($request) {
                $row->column(12, function (Column $column) use ($request) {
                    $oid = $request->input('id');
                    $appid = $request->input('appid');
                    $data = DecreaseSelectHelper::orderInfo($oid,$appid);
                    $column->append((new Box("订单详情", $data))->style('info'));
                });
            });
        });
    }

    /**上传文档首页
     * @param Request $request
     * @return mixed
     */
    public function uploadIndex(Request $request){
        return Admin::content(function (Content $content)use($request) {
            $content->header(trans('backend.decrease_user.header.title'));
            $content->row(function (Row $row) use ($request) {
                $row->column(12, function (Column $column) use ($request) {
                    $data = $request->input();
                    $form = new Form($data);
                    $form->action('/admin/testing/decrease/upload/order?appid='.$request->input('appid'));
                    $form->method('POST');
                    $form->hidden('appid');
                    $form->select('tid',trans('backend.decrease_user.select.testing').'(必选)')->options(json_decode(ParamConfig::getValue('JZ.admin.oder.user.good_title'),true))->rules('required');
                    $form->file('file_name',trans('backend.testing_detail.column.questions_file').'(必选)')->rules('xls,xlsx');
                    $form = $form.'<a href="/admin/testing/decrease/order/download" style="width: 120px;height: 92px;border-radius: 0 0 0 92px;background-color: #3c8dbc;color: #fff;position: absolute;right: -14px;top: -14px;line-height: 70px;text-indent: 18px;text-decoration: none;">下载示例EXCEL</a>';
                    $column->append((new Box("上传文档", $form))->style('info'));
                });
            });
        });
    }

    public function download(){
            return response()->download(
                realpath(base_path('public/upload/decrease')).'/format_order_import.xlsx',
                'format_order_import.xlsx'
            );
    }

    /**上传excel导入数据库
     * @param Request $request
     */
    public function uploadOrder(Request $request){
        $file = Input::file('file_name');
        $appid = base64_decode($request->input('appid'));
        $tid = $request->input('tid');
        if($tid == "0"){
            die('请选择产品类型');
        }
        if(empty($file)){
            die('请选择测评excel');
        }
        if($file) {
            $realPath = $file->getRealPath();
            $entension = $file->getClientOriginalExtension(); //上传文件的后缀.
            $tabl_name = date('YmdHis') . mt_rand(100, 999);
            $newName = $tabl_name . '.' . $entension;
            $path = $file->move(base_path() . '/public/upload/decrease', $newName);
            $cretae_path = base_path() . '/public/upload/decrease/' . $newName;
            DecreaseSelectHelper::importOrder($cretae_path, $tid, $appid);
            $base_url = TestingConfig::getValue('website_url');
            $redirect = $base_url.'/admin/testing/decrease/order/index?appid='.$request->input('appid');
            redirectToUrl($redirect);
        }

    }

    /**订单列表首页
     * @param Request $request
     * @return mixed
     */
    public function orderIndex(Request $request){
        return Admin::content(function (Content $content)use($request) {
            $content->header(trans('backend.decrease_user.header.title'));
            $content->row(function (Row $row) use ($request) {
                $row->column(12, function (Column $column) use ($request) {
                    $str= "";
                    $appid = $request->input('appid');
                    $form = new Form($request->input());
                    $form->action('/admin/testing/decrease/order/index'."?appid=".$appid);
                    $form->method('POST');
                    $form->select('tid',trans('backend.decrease_user.select.testing'))->options(json_decode(ParamConfig::getValue('JZ.admin.oder.user.good_title'),true));
                    $form->select('status',trans('backend.decrease_user.form.status'))->options(["0"=>"请选择","1"=>"未匹配","2"=>"已匹配"]);
                    $form->text('principal',trans('backend.decrease_user.form.principal'));
                    $column->append((new Box('订单筛选', $form))->style('info'));
                });
            });

            $content->row(function (Row $row) use($request){
                $row->column(12, function (Column $column)use($request) {
                    $grid_model = $this->orderGrid($request);
                    $column->append((new Box('订单列表',$grid_model))->style('info'));
                });
            });
        });

    }


    protected function orderGrid($request){
        return Admin::grid(JzOrderDetail::class, function (Grid $grid)use($request){
              $where = array();
              $oid = array();
              $data = $request->input();
              foreach($data as $k => $v){
                  if(empty($v) || $v == "0"){
                      unset($data[$k]);
                  }
              }
              $appidDecode = base64_decode($request->input('appid'));
              $appid =  ['appid', '=',$appidDecode];
              array_push($where,$appid);
              if(isset($data['principal'])){
                  $principal = ['principal', 'like', "%".$data['principal']."%"];
                  array_push($where,$principal);
              }
              if(isset($data['tid'])){
                  $tid = ['tid', '=', $data['tid']];
                  array_push($where,$tid);
              }
              if(isset($data['status'])){//匹配条件
                  $filterUser = DecreaseSelectHelper::filterUser($appidDecode);
                    if($data['status'] == "1"){//未匹配
                        $oid = DecreaseSelectHelper::disFilterUser($appidDecode,$filterUser);
                    }else{//已匹配
                        $oid = $filterUser;
                    }
                  if(count($oid)>0){
                      $grid->model()->where($where)->whereIn('id', $oid)->orderBy('id', 'desc');
                  }else{
                      $grid->model()->where($where)->orderBy('id', 'desc');
                  }
              }else{//排查匹配条件
                  $grid->model()->where($where)->orderBy('id', 'desc');
              }
            $grid->nick_name(trans('backend.decrease_user.form.name'));
            $grid->buyer_name(trans('backend.decrease_user.form.buyer_name'));
            $grid->buyer_sex(trans('backend.decrease_user.form.buyer_sex'));
            $grid->tid(trans('backend.decrease_user.form.testing'));
            $grid->phone(trans('backend.decrease_user.form.phone'));
            $grid->order_time(trans('backend.decrease_user.form.order_time'))->display(function($order_time){
                return date('Y-m-d', strtotime($order_time));
            });
            $grid->number(trans('backend.decrease_user.form.number'));
            $grid->principal(trans('backend.decrease_user.form.principal'));
            $grid->status(trans('backend.decrease_user.form.status'));

            $grid->rows(function($row)use($request,$data){
                $tid = $row->tid;
                $teting = TestingDetailService::getNameByTid($tid);
                $row->column('tid',$teting);
                if(!isset($data['status'])){
                    $relation = JzMatchRelationService::getByOid($row->id);
                    if($relation){
                        $row->column('status','<span class="label label-success">已匹配</span>');
                    }else{
                        $row->column('status','<span class="label label-default">未匹配</span>');
                    }
                }elseif($data['status'] == '1'){
                    $row->column('status','<span class="label label-default">未匹配</span>');
                }elseif($data['status'] == '2'){
                    $row->column('status','<span class="label label-success">已匹配</span>');
                }
                $row->actions('');
                $row->actions()->add(function ($row)use($request) {
                    return "<a href='/admin/testing/decrease/order/info?appid=".$request->input('appid').'&id='."{$row->id}'><i class='fa fa-eye'></i></a>";
                });
                if(MyPermission::check('delete')) {
                    $row->actions()->add(function ($row)use($request) {
                        return "<a href='/admin/testing/decrease/delete/order/".$request->input('appid')."/{$row->id}'><i class='fa fa-trash'></i></a>";
                    });
                }
            });
            $grid->disableFilter();
            $grid->disableBatchDeletion();
            $grid->disableCreation();
            $grid->disableExport();
        });
    }


    /**删除订单
     * @param $appid
     * @param $oid
     */
    public function deleteOrder($appid, $oid){
        $res =  DecreaseSelectHelper::deleteOrder($oid);
        $match = DecreaseSelectHelper::deleteMatch($oid,base64_decode($appid));
        $base_url = TestingConfig::getValue('website_url');
        $redirect = $base_url.'/admin/testing/decrease/order/index?appid='.$appid;
        redirectToUrl($redirect);
    }


    /**匹配首页
     * @param Request $request
     * @return mixed
     */
    public function matchIndex($appid="",$oid="",$tid="",Request $request){
            return Admin::content(function (Content $content)use($appid,$oid,$tid,$request) {
                $content->header(trans('backend.decrease_user.header.title'));
                $content->row(function (Row $row) use($appid,$oid,$tid,$request){
                    $row->column(12, function (Column $column)use($appid,$oid,$tid,$request) {
                        $grid_model =  Admin::grid(WechatUser::class, function (Grid $grid)use($appid,$oid,$tid,$request){
                            $data = $request->input();
                            $where = [];
                            if(!empty($appid)){
                                $appids = ['from_appid', '=',base64_decode($appid)];
                                //$appids = ['from_appid', '=','wx95fc895bebd3743b'];
                                array_push($where,$appids);
                            }else{
                                die('匹配错误');
                            }
                            if(isset($data['nickname'])){
                                $nickname = ['nick_name', 'like', "%".$data['nickname']."%"];
                                array_push($where,$nickname);
                            }else{
                                die('匹配错误');
                            }
                            $grid->model()->where($where);
                            $grid->id('ID')->sortable();
                            $grid->nick_name('微信昵称');
                            $grid->sex('性别')->value(function ($sex) {
                                if($sex == '1'){
                                    return '男';
                                }elseif($sex == '2'){
                                    return '女';
                                }else{
                                    return '保密';
                                }
                            });
                            $grid->headimgurl('头像')->value(function($headimgurl){
                                $heading = TestingConfig::getValue('wechat.user.heading.path');
                                return '<img src="'.$heading.$headimgurl.'">';
                            });
                            $grid->province('省份');
                            $grid->city('城市');
                            $grid->country('国家');
                            $grid->created_at('时间');
                            $grid->rows(function($row)use($appid,$oid,$tid,$request){
                                $row->actions('');
                                $row->actions()->add(function ($row)use($appid,$oid,$tid,$request) {
                                    return "<a href='/admin/testing/decrease/match/order?appid=".$appid.'&tid='.$tid.'&oid='.$oid.'&uid='."{$row->uid}'><button class='btn btn-info' type='button'>匹配</button></a>";
                                });
                            });
                            $grid->disableFilter();
                            $grid->disableBatchDeletion();
                            $grid->disableCreation();
                            $grid->disableExport();
                        });
                        $grid_model .= '<a href="/admin/testing/decrease/people/match?appid='.$appid.'&oid='.$oid.'&tid='.$tid.'"><button class="btn btn-info" type="button">手动匹配</button></a>';
                        $column->append((new Box('匹配列表',$grid_model))->style('info'));
                    });
                });
            });

        }

    public function peopleMatchIndex(Request $request){
        return Admin::content(function (Content $content)use($request) {
            $content->header(trans('backend.decrease_user.header.title'));
            $content->row(function (Row $row) use ($request) {
                $row->column(12, function (Column $column) use ($request) {
                    $form = new Form();
                    $form->action('/admin/testing/decrease/match/index/'.$request->input('appid').'/'.$request->input('oid').'/'.$request->input('tid'));
                    $form->method('GET');
                    $form->text('nickname','微信昵称');
                    $column->append((new Box("手动匹配", $form))->style('info'));
                });
            });
        });
    }



    /**
     *存储匹配关系
     */
    public function matchOrder(Request $request){
        $data = $request->input();
        $result = DecreaseSelectHelper::matchOrder($data);
        if($result){
            $base_url = TestingConfig::getValue('website_url');
            $res = UserRecordService::getByUid($data['uid'],$data['tid']);
            if($res){//已做过题目
                $redirect = $base_url.'/admin/testing/decrease/user/info/'.$res['id'].'/'.$data['uid'].'/'.$data['tid'].'/'.$data['appid'];
            }else{
                $redirect = $base_url.'/admin/testing/decrease/user/info/0/'.$data['uid'].'/'.$data['tid'].'/'.$data['appid'];
            }
            redirectToUrl($redirect);
        }
    }



    /**查询城市 GET /admin/api/china-area/city?q=1
     * @param Request $request
     * @return mixed
     */
    public function city(Request $request)
    {
        $provinceId = $request->get('q');
        $city = ChinaArea::city()->where('parent_id', $provinceId)->get(['id', DB::raw('name as text')])->toArray();
        array_unshift($city,"");
        return $city;
    }

    /**查询地区GET /admin/api/china-area/district?q=1
     * @param Request $request
     * @return mixeds
     */
    public function district(Request $request)
    {
        $cityId = $request->get('q');
        $district = ChinaArea::district()->where('parent_id', $cityId)->get(['id', DB::raw('name as text')])->toArray();
        array_unshift($district,"");
        return $district;
    }

}